from django.http import JsonResponse
from django.views import View
import json
import jwt
from django.db.models import Q
from django.core.paginator import Paginator
from django.utils.decorators import method_decorator
from django_system.role_recognize import check_permission
from user.models import User, Role
from functools import wraps
from .models import College, Classes, Course, UserInfo
from django_system.settings import SECRET_KEY
from break_the_rule.models import Behavior, Rule
from django.db import connection
from examination.models import Score, ExaminationResult


# Create your views here.
class SeeView(View):
    """查看全部学院"""

    def get(self, request, p_id, p_num):
        colleges = College.objects.filter(is_delete=False).all().values()
        college_names = [college['college_name'] for college in list(colleges)]
        paginator = Paginator(colleges, p_num)
        page = paginator.page(p_id)
        if not colleges.values():
            return JsonResponse({'msg': '没有该学院'}, status=400)
        return JsonResponse(
            {'msg': '查看全部学院成功', 'total': len(colleges), 'data': list(page), 'datas': college_names},
            status=200,
            safe=False)


class EditView(View):
    """获取并修改学院信息"""

    @method_decorator(check_permission(['校长', '院长']))
    def get(self, request, id):
        college = College.objects.get(id=id)
        username = User.objects.get(id=college.college_dean_id)
        info = {'name': college.college_name, 'id': college.id, 'time': college.college_create_time,
                'words': college.college_words, 'dean': username.username, 'status': college.college_status}
        d_list = [i['id'] for i in list(college.college_dean.roles.values())]

        return JsonResponse({'msg': '获取指定学院信息成功', 'data': info, 'deans': d_list})

    @method_decorator(check_permission(['校长', '院长']))
    def put(self, request, id):
        data = json.loads(request.body)
        college_name = data['college_name']
        college_create_time = data['college_create_time']
        college_dean = data['college_dean']
        college_status = data['college_status']
        college_words = data['college_words']
        try:
            dean = User.objects.get(username=college_dean)
            College.objects.filter(id=id).update(college_name=college_name, college_create_time=college_create_time,
                                                 college_status=college_status, college_dean=dean,
                                                 college_words=college_words)
            return JsonResponse({'msg': '修改学院信息成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '修改失败'}, status=500)

    @method_decorator(check_permission(['校长']))
    def delete(self, request, id):
        try:
            College.objects.filter(id=id).update(is_delete=True)
            return JsonResponse({'msg': '学院删除成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败'}, status=500)


class AddCollege(View):
    """添加学院信息"""

    @method_decorator(check_permission(['校长']))
    def get(self, request):
        deans = Role.objects.filter(name='院长').first().users.all()
        dean_list = []
        for i in deans:
            if not College.objects.filter(college_dean=i):
                dean_list.append({'id': i.id, 'username': i.username})
        return JsonResponse({'msg': '获取全部院长成功', 'data': dean_list}, status=200)

    @method_decorator(check_permission(['校长']))
    def post(self, request):
        data = json.loads(request.body)
        college_name = data['college_name']
        college_create_time = data['college_create_time']
        college_status = data['college_status']
        college_words = data['college_words']
        college_dean = data['college_dean']
        if not data.values():
            return JsonResponse({'msg': '前端数据不能为空'}, status=400)
        try:
            dean = User.objects.get(id=college_dean)
            College.objects.create(college_name=college_name, college_create_time=college_create_time,
                                   college_status=college_status, college_dean=dean,
                                   college_words=college_words)
            return JsonResponse({'msg': '添加学院成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '添加失败'}, status=500)


class InquireView(View):
    """查看全部班级"""

    @method_decorator(check_permission(['院长']))
    def get(self, request, p_id, p_num):
        token = request.META.get('HTTP_AUTHORIZATION', None).split(' ')[1]
        user = jwt.decode(token, SECRET_KEY, algorithms=['HS256']).get('user')
        user_id = User.objects.filter(username=user).first()
        college = College.objects.filter(college_dean=user_id).first()
        if College.objects.filter(college_dean=user_id).exists():
            classes = Classes.objects.filter(Q(colleges=college) & Q(is_delete=False)).all().values()
            paginator = Paginator(classes, p_num)
            page = paginator.page(p_id)
            if not classes:
                return JsonResponse({'msg': '没有该班级'}, status=400)
            college_name = college.college_name
            return JsonResponse(
                {'msg': '查看全部班级成功', 'total': len(classes), 'data': list(page), 'datas': college_name},
                status=200,
                safe=False)
        else:
            return JsonResponse({'msg': '当前用户不是院长'}, status=400)


class AdditionView(View):
    """添加班级"""

    @method_decorator(check_permission(['院长']))
    def get(self, request):
        teachers = Role.objects.filter(name='老师').first().users.all()
        teacher_list = []
        for i in teachers:
            if not i.classes_user.all():
                teacher_list.append({'id': i.id, 'username': i.username})
        c_teachers = Role.objects.filter(name='班主任').first().users.all()
        c_teacher_list = []
        for i in c_teachers:
            if not i.classes_user.all():
                c_teacher_list.append({'id': i.id, 'username': i.username})
        return JsonResponse({'msg': '获取闲置班主任和老师成功', 'teacher': teacher_list, 'charger': c_teacher_list})

    @method_decorator(check_permission(['院长']))
    def post(self, request):
        data = json.loads(request.body)
        classes_name = data['classes_name']
        classes_status = data['classes_status']
        colleges = data['colleges']
        course = data['course']
        if not data.values():
            return JsonResponse({'msg': '前端数据不能为空'}, status=400)
        try:
            classes = Classes.objects.create(classes_name=classes_name, classes_status=classes_status,
                                             colleges=College.objects.get(college_name=colleges))
            teacher = ''
            c_teacher = ''
            for i in course:
                c = Course.objects.get(id=i)
                classes.course.add(c)
            teachers = Role.objects.filter(name='老师').first().users.all()
            for i in teachers:
                if not i.classes_user.all():
                    teacher = i.id
            c_teachers = Role.objects.filter(name='班主任').first().users.all()
            for i in c_teachers:
                if not i.classes_user.all():
                    c_teacher = i.id
            if teacher:
                classes.user.add(teacher)
            if c_teacher:
                classes.user.add(c_teacher)
            return JsonResponse({'msg': '添加班级信息成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '添加失败'}, status=500)


class AmendView(View):
    """获取并修改班级信息"""

    @method_decorator(check_permission(['校长', '院长']))
    def get(self, request, id):
        class_ = Classes.objects.filter(id=id).first()
        info = {'classes_name': class_.classes_name, 'classes_status': class_.classes_status,
                'colleges': class_.colleges.college_name}
        course_names = [i['id'] for i in class_.course.all().values('id')]
        users = Classes.objects.filter(id=id).first().user.all()
        teacher = 0
        c_teacher = 0
        for i in users:
            if Role.objects.get(name='老师') in i.roles.all():
                teacher = i.username
            if Role.objects.get(name='班主任') in i.roles.all():
                c_teacher = i.username
        return JsonResponse(
            {'msg': '获取指定班级信息成功', 'data': info, 'course_names': course_names, 't_name': teacher,
             'c_name': c_teacher})

    @method_decorator(check_permission(['院长']))
    def put(self, request, id):
        data = json.loads(request.body)
        classes_name = data['classes_name']
        classes_status = data['classes_status']
        colleges = data['colleges']
        course = data['course']
        try:
            colleges = College.objects.get(college_name=colleges)
            classes = Classes.objects.get(id=id)
            classes.course.clear()
            for i in course:
                c = Course.objects.get(id=i)
                classes.course.add(c)
            Classes.objects.filter(id=id).update(classes_name=classes_name, classes_status=classes_status,
                                                 colleges=colleges)
            teacher = ''
            c_teacher = ''
            teachers = Role.objects.filter(name='老师').first().users.all()
            for i in teachers:
                if not i.classes_user.all():
                    teacher = i.id
                    break
            c_teachers = Role.objects.filter(name='班主任').first().users.all()
            for i in c_teachers:
                if not i.classes_user.all():
                    c_teacher = i.id
                    break
            classes.user.clear()
            if teacher:
                classes.user.add(teacher)
            if c_teacher:
                classes.user.add(c_teacher)
            return JsonResponse({'msg': '修改班级基本信息成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '修改失败'}, status=500)

    @method_decorator(check_permission(['校长', '院长']))
    def delete(self, request, id):
        try:
            Classes.objects.filter(id=id).update(is_delete=True)
            return JsonResponse({'msg': '班级删除成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败'}, status=500)


class LookView(View):
    """查看全部课程"""

    def get(self, request):
        course = Course.objects.all().filter(is_delete=False).values()
        if not course:
            return JsonResponse({'msg': '没有该课程'}, status=200)
        return JsonResponse({'msg': '查看全部课程成功', 'data': list(course)},
                            status=200, safe=False)


class CreateCourseView(View):
    """添加课程"""

    @method_decorator(check_permission(['校长', '院长']))
    def post(self, request):
        data = json.loads(request.body)
        course_name = data['course_name']
        course_time = data['course_time']
        end_time = data['end_time']
        colleges = data['colleges']
        if not data.values():
            return JsonResponse({'msg': '前端数据不能为空'}, status=400)
        try:
            courses = Course.objects.create(course_name=course_name, course_time=course_time, end_time=end_time,
                                            colleges=colleges)
            return JsonResponse({'msg': '添加课程成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '添加失败'}, status=500)


class AlterView(View):
    """修改课程信息"""

    @method_decorator(check_permission(['校长', '院长']))
    def put(self, request, id):
        data = json.loads(request.body)
        course_name = data['course_name']
        course_time = data['course_time']
        end_time = data['end_time']
        colleges = data['colleges']
        try:
            Course.objects.filter(id=id).update(course_name=course_name, course_time=course_time, end_time=end_time)
            course = Course.course_colleges.set(colleges)
            course.save()
            return JsonResponse({'msg': '修改课程信息成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '修改失败'}, status=500)


class CancelView(View):
    """删除课程"""

    @method_decorator(check_permission(['校长', '院长']))
    def delete(self, request, id):
        try:
            Course.objects.filter(id=id).update(is_delete=True)
            return JsonResponse({'msg': '删除成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败'}, status=500)


class WatchView(View):
    """查看全部用户详情"""

    def get(self, request, p_id, p_num):
        user_detail = UserInfo.objects.all().values
        user = user_detail.users.all().values()
        paginator = Paginator(user_detail, user, p_num)
        page = paginator.page(p_id)
        if not user_detail:
            return JsonResponse({'msg': '没有该用户'}, status=400)
        return JsonResponse({'msg': '查看全部用户详情成功', 'total': len(user_detail) + len(user), 'data': list(page)},
                            status=200, safe=False)


class AffixView(View):
    """添加用户详情"""

    def post(self, request):
        data = json.loads(request.body)
        number = data['number']
        age = data['age']
        address = data['address']
        parents = data['parents']
        user = data['user']
        if not data.values():
            return JsonResponse({'msg': '前端数据不能为空'}, status=400)
        try:
            UserInfo.objects.create(number=number, age=age, address=address, parents=parents, user=user)
            return JsonResponse({'msg': '用户详情添加成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '添加失败'}, status=500)


class Revamp(View):
    """修改用户详情"""

    def put(self, request, id):
        data = json.loads(request.body)
        number = data['number']
        age = data['age']
        address = data['address']
        parents = data['parents']
        user = data['user']
        try:
            UserInfo.objects.filter(id=id).update(number=number, age=age, address=address, parents=parents)
            user_info = UserInfo.users.set(user)
            user_info.save()
            return JsonResponse({'msg': '修改用户详情成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '修改失败'}, status=500)


class OmitView(View):
    """删除用户详情信息"""

    def delete(self, request, id):
        try:
            UserInfo.objects.filter(id=id).update(is_delete=True)
            return JsonResponse({'msg': '删除成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败'}, status=500)


class BehaviorView(View):
    """老师查看班级违纪信息"""

    @method_decorator(check_permission(['老师', '班主任']))
    def get(self, request, name):
        token = request.META.get('HTTP_AUTHORIZATION', None).split(' ')[1]
        user = jwt.decode(token, SECRET_KEY, algorithms=['HS256']).get('user')
        classes_ = User.objects.filter(username=user).first().classes_user.first().user.all()
        b_class = Classes.objects.filter(classes_name=name).all()
        all_user = []
        for i in b_class:
            for k in i.user.all():
                all_user.append(k)
        break_list = Behavior.objects.filter(break_user__in=all_user).all()
        all_break = [{'id': i.id, 'break_user': i.break_user.username, 'rule': i.rule.name, 'be_time': i.be_time,
                      'description': i.description, 'be_place': i.be_place, 'point': i.rule.point, 'type': i.rule.type}
                     for i in break_list]
        return JsonResponse(
            {'code': 201, 'msg': 'ok!!!!', 'data': all_break, 'total_num': len(classes_), 'break_num': len(all_break)})


class FindScore(View):
    """老师查看自己所在班级学生总体成绩"""

    @method_decorator(check_permission(['老师', '班主任']))
    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION', None).split(' ')[1]
        user = jwt.decode(token, SECRET_KEY, algorithms=['HS256']).get('user')
        user_id = User.objects.filter(username=user).first()
        classes = Classes.objects.filter(user=user_id).all()
        class_score_list = []
        for i in classes:
            if not i.is_delete:
                class_score_dict = {}
                class_name = i.classes_name
                with connection.cursor() as cursor:
                    sql = f"select avg(s.score), c.classes_name,s.exam_date,count(s.score) from examination_result s left join user u on s.stu_id=u.id left join classes_user cu on u.id=cu.user_id left join classes c on cu.classes_id=c.id where c.classes_name='{class_name}' group by c.classes_name,s.exam_date order by  c.classes_name;"
                    cursor.execute(sql)
                    results = cursor.fetchall()
                    score_list = []
                    exam_date_list = []
                    for result in results:
                        score = result[0]
                        score_list.append(int(score))
                        exam_date = result[2]
                        exam_date_list.append(int(exam_date.month))
                    class_score_dict['class_name'] = class_name
                    class_score_dict['exam_date'] = exam_date_list
                    class_score_dict['score'] = score_list
                    class_score_list.append(class_score_dict)
        return JsonResponse({'class_score_list': class_score_list}, status=200, safe=False)


class QueryStuScore(View):
    """查看老师所在班级每个学生的成绩"""

    @method_decorator(check_permission(['老师']))
    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION', None).split(' ')[1]
        user = jwt.decode(token, SECRET_KEY, algorithms=['HS256']).get('user')
        user_id = User.objects.filter(username=user).first()
        classes = Classes.objects.filter(user=user_id).all()
        class_score_list = []
        for i in classes:
            if not i.is_delete:
                class_name = i.classes_name
                students = Classes.objects.filter(classes_name=class_name).first().user.all()
                student_scores = []
                for student in students:
                    scores = ExaminationResult.objects.filter(stu_id=student.id).values('score', 'exam_date')
                    # 添加新的列表
                    student_info = {'class_name': class_name, 'student': student.username}
                    for score in scores:
                        student_info['score'] = score['score']
                        student_info['exam_date'] = score['exam_date']
                        student_scores.append(student_info)
                class_score_list.append({'class_name': class_name, 'student_scores': student_scores})
        return JsonResponse({'class_score_list': class_score_list}, status=200, safe=False)


